<template>
  <view class="message-list">
    <view v-for="(item, index) in messages" :key="index" class="message-item" @click="goChat">
      <image :src="item.avatar" class="message-avatar"></image>
      <view class="message-content-container">
        <view class="message-sender">{{ item.sender }}</view>
        <view class="message-content">{{ item.content }}</view>
        <view class="message-time">{{ item.time }}</view>
        <view v-if="item.unread" class="unread-badge">{{ unreadCount }}</view>
      </view>
    </view>
  </view>
</template>
<script>
let socket;

export default {
  data() {
    return {
      messages: [
        {
          sender: '系统消息',
          content: '欢迎使用本应用',
          time: '2024-01-01 12:00',
          unread: false,
          avatar: '../../static/章若楠.png'
        },
        {
          sender: '用户A',
         content: '你好，有空吗？',
          time: '2024-01-02 14:30',
          unread: true,
          avatar:  '../../static/章若楠.png'
        },
        {
          sender: '用户B',
          content: '项目进度如何？',
          time: '2024-01-03 09:15',
          unread: true,
          avatar: '/static/章若楠.png'
        }
      ],
      unreadCount: 2
    };
  },
  mounted() {
    // 建立小程序 WebSocket 连接
    socket = wx.connectSocket({
      url: 'ws://localhost:8080/chat',
      success: () => {
        console.log('WebSocket 连接请求已发送');
      }
    });

    wx.onSocketOpen(() => {
      console.log('WebSocket 连接已建立');
    });

    wx.onSocketMessage((res) => {
      const message = JSON.parse(res.data);
      // 检查消息是否已存在
      const existingMessage = this.messages.find(msg => msg.content === message.content && msg.time === message.time);
      if (!existingMessage) {
        // 处理接收到的消息
        this.messages.push(message);
        if (message.unread) {
          this.unreadCount++;
        }
      }
    });

    wx.onSocketError((error) => {
      console.error('WebSocket 发生错误:', error);
    });

    wx.onSocketClose(() => {
      console.log('WebSocket 连接已关闭');
    });
  },
  beforeDestroy() {
    // 组件销毁前关闭小程序 WebSocket 连接
    if (socket) {
      wx.closeSocket();
    }
  },
  methods: {
      reconnectWebSocket() {
        if (socket) {
          wx.closeSocket();
        }
        socket = wx.connectSocket({
          url: 'ws://localhost:8080/chat',
          success: () => {
            console.log('WebSocket 重新连接请求已发送');
          }
        });
        wx.onSocketOpen(() => {
          console.log('WebSocket 重新连接已建立');
          this.sendMessage();
        });
        wx.onSocketError((error) => {
          console.error('WebSocket 重新连接发生错误:', error);
        });
      },
	  goChat() {
	  uni.navigateTo({
	    url: '/pages/chat/chat'
	  });
	  },
	  sendMessage() {
	        if (this.inputText.trim()) {
        if (socket && wx.getSocketState().readyState === WebSocket.OPEN) {
	          const message = {
	            content: this.inputText
	          };
	          if (socket && socket.readyState === WebSocket.OPEN) {
	            wx.sendSocketMessage({
            data: JSON.stringify(message),
            success: () => {
              console.log('消息发送成功');
            },
            fail: (error) => {
              console.error('WebSocket 连接未就绪，无法发送消息:', error);
            }
          });
	          } else {
	            console.error('WebSocket 连接未就绪，尝试重新连接...');
        this.reconnectWebSocket();
        return;
	          }
	          this.inputText = '';
	        }
	      }
    
  }
},
}

</script>
<style>
	
.message-list {
  padding: 20rpx;
  background-color: #f4f9ff; /* 浅蓝白色背景，营造清新感 */
  height:670px;
}

.message-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 24rpx; /* 加大消息项间距，更清爽 */
  background-color: white;
  border-radius: 14rpx; /* 加大圆角，视觉更柔和 */
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.12); /* 加深阴影，增强立体感 */
  padding: 24rpx;
}

.message-avatar {
  width: 68rpx;
  height: 68rpx; /* 增大头像尺寸，更突出 */
  border-radius: 50%;
  margin-right: 24rpx;
}

.message-content-container {
  flex: 1;
}

.message-sender {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.message-content {
  font-size: 34rpx;
  color: #333;
  line-height: 1.4; /* 调整行高，提升阅读体验 */
}

.message-time {
  font-size: 26rpx;
  color: #666;
  text-align: right;
}

.unread-badge {
  position: absolute;
  top: 1rpx;
  right: 1rpx;
  background-color: #ff0000; /* 蓝色未读标记，契合主题色 */
  color: white;
  border-radius: 50%;
  width: 44rpx;
  height: 44rpx;
  font-size: 26rpx;
  text-align: center;
  line-height: 44rpx;
}</style>